package com.itwn.springcloud.controller;

import com.itwn.springcloud.entityes.CommonResult;
import com.itwn.springcloud.entityes.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 *      消费者
 *      1.config 配置    RestTemplate
*           @Bean
 *           public RestTemplate getTemplate(){
 *              return  new RestTemplate();
 *          }
 *
 *     2.调用     RestTemplate
 *
 *
 */
@RestController
@Slf4j
public class OrderController {

    //单个提供者, 路由写死
//    public static final String PAYMENT_URL="http://localhost:8001";

    /**
     * ribbon
     * 多个提供者:
     *      要在config中配置,开启 负载均衡@LoadBalanced
     */
    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;

    /**
     * postForObject    post请求
     *
     *  路由  +   参数  +   返回值.class
     * @param payment
     * @return  类似于 json字符串
     */
    @RequestMapping("/consumer/payment/create")
    public CommonResult<Payment> create(@RequestBody Payment payment){
        return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class);
    }

    /**
     * getForObject     get请求
     * @param id
     * @return
     */
    @RequestMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long  id){
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
    }

    /**
     * getForEntity
     *     对象返回,包含一些响应头,响应状态码,响应体等
     * @param id
     * @return
     */
    @GetMapping("/consumer/payment/getForEntity/{id}")
    public CommonResult<Payment> getForEntity(@PathVariable("id") Long id ){

        ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);

        if(entity.getStatusCode().is2xxSuccessful()){       //如果状态成功
            return entity.getBody();    //返回请求体     类似于json字符串
        }else{
            return new CommonResult<>(444,"操作失败");
        }

    }

    @PostMapping("/consumer/payment/postForEntity")
    public CommonResult<Payment> postForEntity(@RequestBody Payment payment){
        ResponseEntity<CommonResult> entity = restTemplate.postForEntity(PAYMENT_URL + "/payment/create", payment, CommonResult.class);

        if(entity.getStatusCode().is2xxSuccessful()){
            return entity.getBody();
        }else{
            return new CommonResult<>(444,"操作失败");
        }

    }


}
